#!/bin/sh
"""": # -*-python-*-
# This command is used by "make clean", so don't rely on ./configure
set -e
for python in \
    python3 \
    python3.9 \
    python3.8 \
    python3.7 \
    python3.6 \
    python \
    python2.7; do \
    if command -v "$python"; then
        exec "$python" "$0" "$@"
    fi
done
echo "error: unable to find suitable python executable; please report" 1>&2
exit 2
"""

from __future__ import absolute_import, print_function
from sys import stderr
import os.path, re, subprocess, sys

def mntent_unescape(x):
    def replacement(m):
        unescapes = {
            "\\\\" : "\\",
            "\\011" : "\t",
            "\\012" : "\n",
            "\\040" : " "
        }
        return unescapes.get(m.group(0))
    return re.sub(r'(\\\\|\\011|\\012|\\040)', replacement, x)

targets = sys.argv[1:]

if not os.path.exists('/proc/mounts'):
    print('No /proc/mounts; skipping mount cleanup in', repr(targets),
          file=stderr)
    sys.exit(0)

exit_status = 0
for target in targets:
    if not os.path.isdir(target):
        print(repr(target), 'is not a directory', file=stderr)
        exit_status = 1
        continue
    top = os.path.realpath(target)
    proc_mounts = open('/proc/mounts', 'r')
    for line in proc_mounts:
        _, point, fstype, _ = line.split(' ', 3)
        point = mntent_unescape(point)
        if top == point or os.path.commonprefix((top + '/', point)) == top + '/':
            if fstype.startswith('fuse'):
                if subprocess.call(['fusermount', '-uz', point]) != 0:
                    exit_status = 1
            else:
                if subprocess.call(['umount', '-l', point]) != 0:
                    exit_status = 1

sys.exit(exit_status)
